import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/pre_sale/state.dart';
import 'package:yp/pages/order_settlement/view.dart';
import 'package:yp/services/api.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:yp/utils/util.dart';

import '../../../router.dart';

class PreSaleActiveLogic extends GetxController {
  PreSaleActiveState state = PreSaleActiveState();
  var locationResult;
  Timer timer;
  Timer surplusTimer;

  @override
  void onInit() {
    super.onInit();
    print('Get.arguments ==> ${Get.arguments}');
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);
    if (Get.arguments != null) {
      if (Get.arguments['model']!=null) {
        state.linktarget = Get.arguments['model']['linktarget'];
        state.shopId =Get.arguments['model']['shop_id'] ?? shopInfo['shop_id'] ;
      }else{
        state.linktarget = Get.arguments['linktarget'];
        state.shopId =Get.arguments['shopId'] ?? shopInfo['shop_id'] ;
      }
    } else {
      state.linktarget = getQueryVariable('linktarget');
      state.shopId = getQueryVariable('shopId');
      // if (SpUtil.getInt('empeNumId') == 0 ||
      //     SpUtil.getInt('empeNumId') == null) {
      //   Get.offAllNamed(RouteConfig.mallLogin, arguments: {
      //     'linktarget': state.linktarget,
      //     'shopId': state.shopId
      //   });
      //   return;
      // }
    }
    // locationResult = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
    // print('--------------------------');
    // print(locationResult);
    // print(locationResult['AMapResult']);
    getPreSale();
  }

  @override
  void onClose() {
    super.onClose();
    timer?.cancel();
    timer = null;
    cancelTimer();
  }

  void getPreSale() {
    if (state.shopId == null) {
      return;
    }
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "ecactivity_id": state.linktarget,
      "from_where": "mobile",
      "shop_id": state.shopId,
      "shop_num_id": state.shopId,
      "page_no": 1,
      "page_size": 100,
      // 'prv_num_id': defaultAddress['p_code'],
      // 'city_num_id': defaultAddress['city_code'],
      // 'city_area_num_id': defaultAddress['ad_code'],
    };
    Api.getPreSale(params).listen((event) {
      print('$event---$params');
      if (event != null && event['code'] == 0) {
        if (event['seckill_items'] == null) {
          toast('活动未开始或已结束');
          // timer = Timer(Duration(milliseconds: 1500), () {
          //   Navigator.of(Get.context).pop();
          // });
        } else {
          state.seckillItems = event['seckill_items'];
          state.seckillActivity = event['seckill_activity'];
          String slideImages = event['seckill_activity']['slide_images'];
          state.slideImages = slideImages?.split(',') ?? [];
          state.title = event['seckill_activity']['ecactivity_name'] ?? '';
          state.activityStatus = event['seckill_activity']['activity_status'];
          formatStringDateTime(event['seckill_activity']['end_time'] ?? '');
          startTimer();
          update();
        }
      } else {
        toast(event != null ? event['message'] : '请求失败');
      }
    });
  }

  void formatStringDateTime(String preEndTime) {
    if (preEndTime == '') {
      state.surplusTime = 0;
      return;
    }
    DateTime time = DateTime.now();
    DateTime endTime = DateTime.parse(preEndTime).toUtc();
    Duration different = endTime.difference(time);
    state.surplusTime = different.inSeconds;
  }

  void startTimer() {
    // 设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    surplusTimer = Timer.periodic(period, (timer) {
      if (state.surplusTime <= 0) {
        // 倒计时秒数为0，取消定时器
        cancelTimer();
      }
      //更新界面
      //秒数减一，因为一秒回调一次
      state.surplusTime--;
      // state.countContent = constructTime(state.surplusTime);
      state.surplusWidget = widgetConStructTime(state.surplusTime);
      update();
    });
  }

  void cancelTimer() {
    if (surplusTimer != null) {
      surplusTimer.cancel();
      surplusTimer = null;
    }
  }

  Widget _conStructCard(String data) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
      margin: const EdgeInsets.symmetric(horizontal: 2),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: const Color(0xff888888),
          borderRadius: BorderRadius.circular(3),
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: const [Color(0xff999999), Color(0xff222222)],
          )),
      child: Text(
        data,
        style: TextStyle(
          color: const Color(0xffffffff),
          fontSize: 12,
        ),
      ),
    );
  }

  Widget widgetConStructTime(num mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return Row(
      children: [
        _conStructCard(days.toString()),
        Text('天', style: TextStyle(fontSize: 12)),
        _conStructCard(hours.toString()),
        Text('时', style: TextStyle(fontSize: 12)),
        _conStructCard(minutes.toString()),
        Text('分', style: TextStyle(fontSize: 12)),
        _conStructCard(seconds.toString()),
        Text('秒', style: TextStyle(fontSize: 12)),
      ],
    );
  }

  String constructTime(double mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return days.toString() +
        "天" +
        hours.toString() +
        "时" +
        minutes.toString() +
        "分" +
        seconds.toString() +
        "秒";
  }

  String constructVipTime(int seconds) {
    int day = seconds % 1000 ~/ 3600 ~/ 24;
    int hour = seconds % 1000 ~/ 3600;
    int minute = seconds % 1000 % 3600 ~/ 60;
    int second = seconds % 1000 % 60;
    return formatTime(day) +
        '天' +
        formatTime(hour) +
        "小时" +
        formatTime(minute) +
        "分" +
        formatTime(second);
  }

  // 数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  void shareToFriend() {

    var data = Config.H5_URL+'&isGoPresellAct=true&id='+state.seckillActivity['ecactivity_id'].toString()+'&currentShopId='+state.shopId.toString();
    // var data = Config.WEB_URL +
    //     'preSaleActive?linktarget=${state.linktarget}&shopId=${state.shopId}';
    print( "state.seckillActivity[']");
    print( state.seckillActivity);

    var model = fluwx.WeChatShareWebPageModel(
      data,
      description: state.seckillActivity['ecactivity_brief_intro'],
      title: state.seckillActivity['share_desc'],
      thumbnail: fluwx.WeChatImage.network(
          state.seckillActivity['share_images']),
      scene: fluwx.WeChatScene.SESSION,
    );
    fluwx.shareToWeChat(model);
  }

  // 分享朋友圈
  void shareToWechatCircle() {
    print(state.seckillActivity);
    var detail;
    if (state.seckillActivity != null) {
      detail = state.seckillActivity;
    } else {
      return;
    }
    print('---------------分享朋友圈--------------------');
    print(detail);
    // 处理发布到朋友圈
    if (state.slideImages == null || state.slideImages.length == 0) {
      toast("分享失败，未获取到图片地址");
      return;
    }
    var data = Config.H5_URL+'&isGoPresellAct=true&id='+state.seckillActivity['ecactivity_id'].toString()+'&currentShopId='+state.shopId.toString();;
    // var data = Config.WEB_URL +
    //     'preSaleActive?linktarget=${state.linktarget}&shopId=${state.shopId}';
    print('朋友圈分享链接: $data');
    var model = fluwx.WeChatShareWebPageModel(
      data,
      description: state.seckillActivity['ecactivity_brief_intro'],
      title: state.seckillActivity['share_desc'],
      thumbnail: fluwx.WeChatImage.network(
          state.seckillActivity['share_images']),
      scene: fluwx.WeChatScene.TIMELINE,
    );
    fluwx.shareToWeChat(model);
  }
}
